<?php

namespace app\admin\model\rebate;

use think\Log;
use think\Model;


class Rebate extends Model
{





    // 表名
    protected $name = 'rebate_list';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [

    ];
    /**
     * 类型
     */
    public function getTypeInfo()
    {
        return [
            4=>'订单支付',
            5=>'代理升级',
            6=>'成功邀请',
            7=>'团队成员',
            9=>'成功回购',
            12=>'团队收益',
            13=>'团队收益',
            20=>'寄售收入',
        ];
    }

    /**
     * 返佣记录添加
     */
    public static function saveRebateInfo($data)
    {
        $info = [
            "uid" => $data['uid'],
            "orderId" => $data['orderId'] ? $data['orderId'] : time(),
            "disUid" => isset($data['disUid']) ? $data['disUid'] : 0,
            "level" => isset($data['level']) ? $data['level'] : 0,
            "percent" => isset($data['percent']) ? $data['percent'] : 100,
            "type" => $data['type'],
            "price" => $data['price'],
            "status" => 1,
            "date"=>date("Y-m-d"),
        ];
        $rebate = self::where("uid",$info['uid'])->where('orderId',$info['orderId'])->where('type',$info['type'])->find();
        if(empty($rebate)){
            self::create($info);
            \app\common\model\User::money($data['uid'], $data['price'], $data['type'], $data['info'],$info['orderId']);
        }
    }
    /**
     * 订单支付完成
     */
    public static function confirmRebate($orderId)
    {
        $order = \app\admin\model\SpellOrder::where('orderId',$orderId)->where('model',2)->find();
        if(empty($order)){
            return false;
        }
        $shareUid = 0;
        //分享赚
        //1 自己开团上级拿钱
        //2 手动点击参上级团拿钱
        $upUser = \app\admin\model\User::where('id',$order['uid'])->find();
        if(!empty($order['fromUid'])){
            $isUserSpell = \app\admin\model\user\Spell::where('uid',$order['uid'])->where('fromUid',$order['fromUid'])->where('ptid',$order['ptid'])->where('status',3)->find();
            if(!empty($isUserSpell)){
                if($isUserSpell['type'] == 2){
                    //$shareUid = $order['fromUid'];
                }elseif($isUserSpell['type'] == 1){
                    $upSpellOrder = \app\admin\model\SpellOrder::where('id',$isUserSpell['ptid'])->find();
                    if($upSpellOrder['uid'] != $upUser['referee']){
                        $shareUid = $order['fromUid'] ==$upSpellOrder['uid']?$upUser['referee']:$order['fromUid'];
                    }
                }
            }
        }else{
            if($upUser['referee']>0){
                $shareUid = $upUser['referee'];
            }
        }
        if(!empty($shareUid)){//分享人拿钱
            $percent = \think\config::get("site.pingsharepercent");
            $price = bcmul($order['payPrice'],$percent*0.01,2);
           /* $activitytimelimitstatus = \think\config::get("site.activitytimelimitstatus");
            $activitytimelimitsuccess = \think\config::get("site.activitytimelimitsuccess");
            $activitytimelimitbei = \think\config::get("site.activitytimelimitbei");
            $activitytimelimitstarttime = \think\config::get("site.activitytimelimitstarttime");
            if($activitytimelimitstatus == 1 && $activitytimelimitsuccess>0 && $activitytimelimitbei>0){
                $starttime = strtotime(date($activitytimelimitstarttime,time()));
                $countNum = \app\admin\model\SpellOrder::where('fromUid',$order['fromUid'])->where('uid','<>',$order['uid'])->where('payStatus',1)->where('createtime','>',$starttime)->count();
                if($countNum>=$activitytimelimitsuccess){
                    $price = bcadd($price,bcmul($price,$activitytimelimitbei,2),2);
                }
            }*/
//            if($price>0){
//                \app\admin\model\rebate\Rebate::saveRebateInfo([
//                    "uid"=>$shareUid,
//                    "disUid"=>$order['uid'],
//                    "orderId"=>$orderId,
//                    "type"=>6,
//                    "percent"=>$percent,
//                    "price"=>$price,
//                    "info"=>'分享会员参团',
//                ]);
//                \app\common\library\Sms::otherSend([
//                    "uid"=>$shareUid,
//                    "type"=>7,
//                    "mobile"=>substr($order['mobile'], 7,4),
//                    "price"=>$price,
//                ]);
//            }
        }

        $user = \app\admin\model\User::where('id',$order['uid'])->find();
        $relation  = explode("-",$user['relation']);
        $rebateArr=[];
        if($relation[0]>0){
            $currentLevel=1;
            foreach ($relation as $ks=>$vs){
                $level = $ks+1;
                if($vs<=0){
                    continue;
                }
                $upUser = \app\admin\model\User::where('id',$vs)->where('agent','>=',0)->find();
                if(empty($upUser)){
                    continue;
                }
                if($currentLevel<=$upUser['agent']){
                    $currentLevel=$upUser['agent'];
                }
                if($upUser['agent']>=$currentLevel && $upUser['agent']<6){
                    $rebateArr[$currentLevel][]=$vs;
                }else{
                    continue;
                }
            }
            $prevPing=$i=0;
            foreach ($rebateArr as $key=>$row){
                $agent = \app\admin\model\agent\Agent::where('id',$key)->find();
                if($i>0){
                    $percent=$agent['ping']-$prevPing;
                    $prevPing=$agent['ping'];
                }else{
                    $prevPing=$percent=$agent['ping'];
                }
                $price = bcmul($order['payPrice'],$percent*0.01,2);
                $price = bcdiv($price,count($row),2);
                foreach ($row as $vs){
                    \app\admin\model\rebate\Rebate::saveRebateInfo([
                        "uid"=>$vs,
                        "disUid"=>$user['id'],
                        "orderId"=>$orderId,
                        "level"=>$key,
                        "type"=>7,
                        "percent"=>$agent["ping"],
                        "price"=>$price,
                        "info"=>'会员参团奖金',
                    ]);
                    \app\common\library\Sms::otherSend([
                        "uid"=>$vs,
                        "type"=>8,
                        "level"=>\app\admin\model\User::where('id',$vs)->value('agent'),
                        "price"=>$price,
                    ]);
                }
                $i++;
            }

        }
        return true;
    }

}
